<template>
  <div class="replenish-rules-page">
    <!-- 页面头部 -->
    <el-card class="header-card">
      <div class="page-header">
        <div>
          <h2>补货规则配置</h2>
          <p class="subtitle">配置商品的安全库存、补货周期、采购策略等智能补货规则</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showBatchSettingDialog">
            <el-icon><Setting /></el-icon>
            批量设置
          </el-button>
          <el-button type="success" @click="handleImport">
            <el-icon><Upload /></el-icon>
            导入规则
          </el-button>
          <el-button @click="handleExport">
            <el-icon><Download /></el-icon>
            导出规则
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 筛选区域 -->
    <el-card style="margin-top: 20px">
      <div class="filter-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable style="width: 180px" />
          </el-form-item>
          <el-form-item label="商品编码">
            <el-input v-model="searchForm.code" placeholder="请输入商品编码" clearable style="width: 150px" />
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select v-model="searchForm.category" placeholder="请选择分类" clearable style="width: 150px">
              <el-option label="电子产品" value="electronics" />
              <el-option label="食品饮料" value="food" />
              <el-option label="服装鞋帽" value="clothing" />
              <el-option label="日用百货" value="daily" />
            </el-select>
          </el-form-item>
          <el-form-item label="仓库">
            <el-select v-model="searchForm.warehouse" placeholder="请选择仓库" clearable style="width: 150px">
              <el-option label="主仓库" value="main" />
              <el-option label="分仓库A" value="branchA" />
              <el-option label="分仓库B" value="branchB" />
            </el-select>
          </el-form-item>
          <el-form-item label="规则状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="已启用" value="enabled" />
              <el-option label="已禁用" value="disabled" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><RefreshLeft /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 规则列表 -->
    <el-card style="margin-top: 20px">
      <el-table
        :data="rulesList"
        v-loading="loading"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="code" label="商品编码" width="120" />
        <el-table-column prop="name" label="商品名称" min-width="150">
          <template #default="{ row }">
            <div class="product-name">
              <el-image
                :src="row.image"
                style="width: 40px; height: 40px; margin-right: 8px"
                fit="cover"
              />
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="warehouse" label="仓库" width="100" />
        <el-table-column prop="safetyStock" label="安全库存" width="100" align="right" />
        <el-table-column prop="maxStock" label="最大库存" width="100" align="right" />
        <el-table-column prop="minOrderQty" label="最小订货量" width="110" align="right" />
        <el-table-column prop="orderBatch" label="订货批量" width="100" align="right" />
        <el-table-column prop="replenishCycle" label="补货周期" width="100" align="center">
          <template #default="{ row }">
            {{ row.replenishCycle }} 天
          </template>
        </el-table-column>
        <el-table-column prop="leadTime" label="采购提前期" width="110" align="center">
          <template #default="{ row }">
            {{ row.leadTime }} 天
          </template>
        </el-table-column>
        <el-table-column prop="strategy" label="补货策略" width="120">
          <template #default="{ row }">
            <el-tag :type="getStrategyType(row.strategy)">
              {{ getStrategyName(row.strategy) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="enabled"
              inactive-value="disabled"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button link type="success" @click="handleCopy(row)">
              <el-icon><DocumentCopy /></el-icon>
              复制
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑规则对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editForm.id ? '编辑补货规则' : '新增补货规则'"
      width="800px"
    >
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品编码" prop="code">
              <el-input v-model="editForm.code" placeholder="请输入商品编码" :disabled="!!editForm.id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="editForm.name" placeholder="请输入商品名称" :disabled="!!editForm.id" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouse">
              <el-select v-model="editForm.warehouse" placeholder="请选择仓库" style="width: 100%">
                <el-option label="主仓库" value="main" />
                <el-option label="分仓库A" value="branchA" />
                <el-option label="分仓库B" value="branchB" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="补货策略" prop="strategy">
              <el-select v-model="editForm.strategy" placeholder="请选择策略" style="width: 100%">
                <el-option label="定量订货" value="fixed" />
                <el-option label="定期订货" value="periodic" />
                <el-option label="经济订货量" value="eoq" />
                <el-option label="需求预测" value="forecast" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">库存参数</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="安全库存" prop="safetyStock">
              <el-input-number
                v-model="editForm.safetyStock"
                :min="0"
                :step="10"
                style="width: 100%"
              />
              <div class="form-tip">
                <el-icon><InfoFilled /></el-icon>
                低于此值将触发补货
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大库存" prop="maxStock">
              <el-input-number
                v-model="editForm.maxStock"
                :min="0"
                :step="10"
                style="width: 100%"
              />
              <div class="form-tip">
                <el-icon><InfoFilled /></el-icon>
                库存上限，避免积压
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">订货参数</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最小订货量" prop="minOrderQty">
              <el-input-number
                v-model="editForm.minOrderQty"
                :min="1"
                :step="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订货批量" prop="orderBatch">
              <el-input-number
                v-model="editForm.orderBatch"
                :min="1"
                :step="10"
                style="width: 100%"
              />
              <div class="form-tip">
                <el-icon><InfoFilled /></el-icon>
                必须是此值的整数倍
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="补货周期" prop="replenishCycle">
              <el-input-number
                v-model="editForm.replenishCycle"
                :min="1"
                :max="365"
                style="width: 100%"
              />
              <span style="margin-left: 8px">天</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购提前期" prop="leadTime">
              <el-input-number
                v-model="editForm.leadTime"
                :min="0"
                :max="365"
                style="width: 100%"
              />
              <span style="margin-left: 8px">天</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">高级设置</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplier">
              <el-select v-model="editForm.supplier" placeholder="请选择供应商" style="width: 100%">
                <el-option label="供应商A" value="supplierA" />
                <el-option label="供应商B" value="supplierB" />
                <el-option label="供应商C" value="supplierC" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="editForm.priority" placeholder="请选择优先级" style="width: 100%">
                <el-option label="高" value="high" />
                <el-option label="中" value="medium" />
                <el-option label="低" value="low" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="自动审核" prop="autoApprove">
          <el-switch v-model="editForm.autoApprove" />
          <span style="margin-left: 10px; color: #909399; font-size: 12px">
            启用后，补货单将自动审核通过
          </span>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="editForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 批量设置对话框 -->
    <el-dialog v-model="batchDialogVisible" title="批量设置规则" width="600px">
      <el-alert
        title="批量设置提示"
        type="info"
        description="批量设置将应用到所有选中的商品，请谨慎操作"
        :closable="false"
        style="margin-bottom: 20px"
      />
      
      <el-form :model="batchForm" label-width="120px">
        <el-form-item label="安全库存">
          <el-input-number v-model="batchForm.safetyStock" :min="0" :step="10" style="width: 100%" />
        </el-form-item>
        <el-form-item label="最大库存">
          <el-input-number v-model="batchForm.maxStock" :min="0" :step="10" style="width: 100%" />
        </el-form-item>
        <el-form-item label="补货周期">
          <el-input-number v-model="batchForm.replenishCycle" :min="1" style="width: 100%" />
          <span style="margin-left: 8px">天</span>
        </el-form-item>
        <el-form-item label="补货策略">
          <el-select v-model="batchForm.strategy" placeholder="请选择策略" style="width: 100%">
            <el-option label="定量订货" value="fixed" />
            <el-option label="定期订货" value="periodic" />
            <el-option label="经济订货量" value="eoq" />
            <el-option label="需求预测" value="forecast" />
          </el-select>
        </el-form-item>
        <el-form-item label="自动审核">
          <el-switch v-model="batchForm.autoApprove" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="batchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  category: '',
  warehouse: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const selectedRows = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const rulesList = ref([
  {
    id: 1,
    code: 'P001',
    name: 'iPhone 14 Pro Max 256GB',
    image: 'https://via.placeholder.com/40',
    warehouse: '主仓库',
    safetyStock: 30,
    maxStock: 100,
    minOrderQty: 10,
    orderBatch: 5,
    replenishCycle: 7,
    leadTime: 7,
    strategy: 'forecast',
    supplier: '供应商A',
    priority: 'high',
    autoApprove: true,
    status: 'enabled'
  },
  {
    id: 2,
    code: 'P002',
    name: '华为 Mate 50 Pro',
    image: 'https://via.placeholder.com/40',
    warehouse: '主仓库',
    safetyStock: 25,
    maxStock: 80,
    minOrderQty: 10,
    orderBatch: 5,
    replenishCycle: 7,
    leadTime: 5,
    strategy: 'fixed',
    supplier: '供应商B',
    priority: 'medium',
    autoApprove: false,
    status: 'enabled'
  },
  {
    id: 3,
    code: 'P003',
    name: '小米13 Ultra',
    image: 'https://via.placeholder.com/40',
    warehouse: '分仓库A',
    safetyStock: 20,
    maxStock: 60,
    minOrderQty: 10,
    orderBatch: 10,
    replenishCycle: 10,
    leadTime: 6,
    strategy: 'periodic',
    supplier: '供应商C',
    priority: 'high',
    autoApprove: true,
    status: 'enabled'
  },
  {
    id: 4,
    code: 'P004',
    name: 'OPPO Find X6 Pro',
    image: 'https://via.placeholder.com/40',
    warehouse: '主仓库',
    safetyStock: 30,
    maxStock: 70,
    minOrderQty: 5,
    orderBatch: 5,
    replenishCycle: 14,
    leadTime: 5,
    strategy: 'eoq',
    supplier: '供应商A',
    priority: 'medium',
    autoApprove: false,
    status: 'enabled'
  },
  {
    id: 5,
    code: 'P005',
    name: 'vivo X90 Pro+',
    image: 'https://via.placeholder.com/40',
    warehouse: '分仓库B',
    safetyStock: 25,
    maxStock: 65,
    minOrderQty: 10,
    orderBatch: 5,
    replenishCycle: 7,
    leadTime: 6,
    strategy: 'forecast',
    supplier: '供应商B',
    priority: 'high',
    autoApprove: true,
    status: 'disabled'
  }
])

total.value = rulesList.value.length

// 编辑对话框
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  id: null,
  code: '',
  name: '',
  warehouse: '',
  safetyStock: 0,
  maxStock: 0,
  minOrderQty: 1,
  orderBatch: 1,
  replenishCycle: 7,
  leadTime: 0,
  strategy: 'forecast',
  supplier: '',
  priority: 'medium',
  autoApprove: false,
  remark: ''
})

const editRules = {
  code: [{ required: true, message: '请输入商品编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  warehouse: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  safetyStock: [{ required: true, message: '请输入安全库存', trigger: 'blur' }],
  maxStock: [{ required: true, message: '请输入最大库存', trigger: 'blur' }],
  strategy: [{ required: true, message: '请选择补货策略', trigger: 'change' }]
}

// 批量设置对话框
const batchDialogVisible = ref(false)
const batchForm = reactive({
  safetyStock: null,
  maxStock: null,
  replenishCycle: null,
  strategy: '',
  autoApprove: false
})

// 获取策略名称
const getStrategyName = (strategy) => {
  const map = {
    fixed: '定量订货',
    periodic: '定期订货',
    eoq: '经济订货量',
    forecast: '需求预测'
  }
  return map[strategy] || strategy
}

// 获取策略类型
const getStrategyType = (strategy) => {
  const map = {
    fixed: '',
    periodic: 'warning',
    eoq: 'success',
    forecast: 'primary'
  }
  return map[strategy] || ''
}

// 搜索
const handleSearch = () => {
  loading.value = true
  setTimeout(() => {
    ElMessage.success('查询完成')
    loading.value = false
  }, 500)
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 状态变化
const handleStatusChange = (row) => {
  const status = row.status === 'enabled' ? '启用' : '禁用'
  ElMessage.success(`已${status}该规则`)
}

// 编辑
const handleEdit = (row) => {
  Object.assign(editForm, { ...row })
  editDialogVisible.value = true
}

// 复制
const handleCopy = (row) => {
  const newRow = { ...row, id: null, code: row.code + '_copy', name: row.name + '（复制）' }
  Object.assign(editForm, newRow)
  editDialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除商品 ${row.name} 的补货规则吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

// 保存
const handleSave = () => {
  editFormRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('保存成功')
      editDialogVisible.value = false
    }
  })
}

// 显示批量设置对话框
const showBatchSettingDialog = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要设置的商品')
    return
  }
  batchDialogVisible.value = true
}

// 批量保存
const handleBatchSave = () => {
  ElMessage.success(`已为 ${selectedRows.value.length} 个商品设置规则`)
  batchDialogVisible.value = false
}

// 导入
const handleImport = () => {
  ElMessage.info('导入功能开发中')
}

// 导出
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 分页
const handleSizeChange = (size) => {
  pageSize.value = size
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}
</script>

<style scoped lang="scss">
.replenish-rules-page {
  padding: 20px;

  .header-card {
    .page-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h2 {
        margin: 0 0 8px 0;
        color: #303133;
      }

      .subtitle {
        margin: 0;
        color: #909399;
        font-size: 14px;
      }

      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
  }

  .filter-area {
    padding: 15px;
    background: #f5f7fa;
    border-radius: 4px;
  }

  .product-name {
    display: flex;
    align-items: center;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .form-tip {
    display: flex;
    align-items: center;
    gap: 4px;
    margin-top: 4px;
    font-size: 12px;
    color: #909399;
  }
}
</style>

